﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using VentaElectrodomesticos.Datos;
using VentaElectrodomesticos.Negocio;
using VentaElectrodomesticos.Contrato;

namespace VentaElectrodomesticos.Login
{
    public partial class FormLogin : Form
    {
        public Usuario usuario { get; set; }
        private static DialogResult result;
        public int intentos = 0;
        public int invalidPasswordIntentos = 0;

        public FormLogin()
        {
            InitializeComponent();
        }

        /*
         * Ya se que está harcodeado... hay que crear la tabla en la base... 
         */
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                usuario = new UsuarioNegocio().authenticate(tUser.Text, SHAEncrypt.encode(tPass.Text));
                result = DialogResult.OK;
                Close();
            }
            catch (UsuarioNotFoundException ex)
            {
                result = DialogResult.Cancel;
                intentos++;
                MessageBox.Show(ex.Message);
            }
            catch (InvalidPasswordException ex)
            {
                result = DialogResult.Cancel;
                invalidPasswordIntentos++;
                intentos++;
                MessageBox.Show(ex.Message);
            } catch (NegocioException) {
                MessageBox.Show("Error inesperado, consulte con su administrador.");
            }
            catch (DatosException)
            {
                MessageBox.Show("Error inesperado, consulte con su administrador.");
            }

            if (intentos == 3) {
                Close();
            }
        }

        private void bCancel_Click(object sender, EventArgs e)
        {
            result = DialogResult.Cancel;
            this.Close();
        }

        public DialogResult getResult()
        {
            return result;
        }

        private void FormLogin_Load(object sender, EventArgs e)
        {
            this.tPass.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckKeys);
            this.tUser.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckKeys);
        }

        private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                button1_Click(sender, new EventArgs());
        }
    }
}
